const puppeteer = require('puppeteer');

(async () => {
    const start = new Date().getTime();

    const browser = await puppeteer.launch({
        timeout: 15000,
        headless: false
    });
    const page = await browser.newPage();

    // await page.goto('https://www.1688.com');
    // await page.waitFor(1000);
    // await page.click('#j-identity > div > span > i');
    //
    // const input = await page.$('#sm-widget-upload > div > input[type="file"]');
    // await input.uploadFile(`${__dirname}/images/test.jpg`);
    // await page.evaluate(() => document.querySelector('#sm-widget-upload > div > input[type="file"]')
    //     .addEventListener('click', e => e.preventDefault()));
    // await page.click('#sm-widget-picbtn');
    //
    // await page.waitFor(5000);
    //
    // console.log(page.url());

    await page.goto('https://s.1688.com/youyuan/index.htm?tab=imageSearch&imageType=oss&imageAddress=cbuimgsearch/zHGN2pX3P41537928695000.jpg&spm=a260k.635.3262836.d1088');

    let preScrollHeight = 300,
        scrollHeight = -1,
        step = 400;
    while (preScrollHeight !== scrollHeight) {
        await page.evaluate(height => window.scrollTo(0, height), preScrollHeight);

        preScrollHeight += step;

        await page.waitFor(1300);

        scrollHeight = await page.evaluate(async () => {
            return document.body.scrollHeight;
        });

        preScrollHeight = preScrollHeight > scrollHeight ? scrollHeight : preScrollHeight;
    }
    // for (let i = 0; i < 1; i++) {
    //     try {
    //         await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
    //         await page.waitForNavigation({
    //             timeout: 3000, waitUntil: ['networkidle0']
    //         });
    //     } catch (e) {
    //     }
    // }

    const products = await page.evaluate(sel => {
        const arr = [];

        document.querySelectorAll(sel).forEach(one => {
            arr.push({
                name: one.querySelector('div.sm-offer-title.sw-dpl-offer-title > a').title,
                image: one.querySelector('div.sm-offer-main > div.sm-offer-photo.sw-dpl-offer-photo > a > img').src,
                price: one.querySelector('div.sm-offer-main > div.sm-offer-price.sw-dpl-offer-price > span').title,
                url: one.querySelector('div.sm-offer-title.sw-dpl-offer-title > a').href
            });
        });

        return arr;
    }, '#sm-offer-list > li');

    console.log(products);

    console.log(`总耗时：${((new Date().getTime() - start) / 1000).toFixed(2)}s`);
})();